<script setup lang="tsx">
import { computed, reactive, ref, shallowRef, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import type { Org } from '@/service/api';
import { createOrg, fetchAllOrgOptions, fetchUserOptionsPage, updateOrg } from '@/service/api';
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict';

defineOptions({
  name: 'OrgOperateModal'
});

export type OperateType = NaiveUI.TableOperateType;

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit menu data or the parent menu data when adding a child menu */
  rowData?: Org | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule, patternRules } = useFormRules();

const submitLoading = ref(false);

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('page.manage.org.addOrg'),
    edit: $t('page.manage.org.editOrg')
  };
  return titles[props.operateType];
});

type Model = Pick<Org, 'parentId' | 'name' | 'sort' | 'status' | 'leaderUserId' | 'phone' | 'email'> & {
  id: number | null;
};

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: null,
    parentId: -1,
    name: '',
    sort: 0,
    status: 1,
    leaderUserId: null,
    phone: '',
    email: ''
  };
}

type RuleKey = Extract<keyof Model, 'name' | 'status' | 'sort' | 'parentId' | 'phone' | 'email'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  status: defaultRequiredRule,
  sort: defaultRequiredRule,
  parentId: defaultRequiredRule,
  phone: patternRules.phone,
  email: patternRules.email
};

function closeDrawer() {
  submitLoading.value = false;
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  submitLoading.value = true;

  if (props.operateType === 'edit') {
    // request
    const { error } = await updateOrg(model.id as number, model);

    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  } else {
    const { error } = await createOrg(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
}

const orgOptions = shallowRef<Api.Common.TreeOptions[]>([]);

/** 获取机构树，下拉选项 */
async function getOrgTreeOptions() {
  const res = await fetchAllOrgOptions();

  if (!res.error) {
    orgOptions.value = res.data;
  }
}

type UserOptionsModle = {
  page: number;
  pageSize: number;
  itemCount: number;
  userName: string;
};

const userOptions = shallowRef<Api.Common.Options[]>([]);
const userOptionsLoading = ref(false);

const optionsValue: UserOptionsModle = reactive(createOptionsModel());

function createOptionsModel(): UserOptionsModle {
  return {
    page: 1,
    pageSize: 10,
    itemCount: 0,
    userName: ''
  };
}

/** 获取用户列表，下拉选项 */
async function getUserOptions(item: string) {
  userOptionsLoading.value = true;

  const params = {
    nickname: item,
    current: optionsValue.page,
    size: optionsValue.pageSize
  };

  window.setTimeout(async () => {
    const res = await fetchUserOptionsPage(params);

    if (!res.error) {
      userOptions.value = res.data.records;
      optionsValue.page = res.data.current;
      optionsValue.pageSize = res.data.size;
      optionsValue.itemCount = res.data.total;
    }

    userOptionsLoading.value = false;
  }, 800);
}

const handleOptionsPage = (page: number) => {
  optionsValue.page = page;
  getUserOptions('');
};

const optionsClear = () => {
  getUserOptions('');
};

const handleOptionsPageSize = (pageSize: number) => {
  optionsValue.pageSize = pageSize;
  getUserOptions('');
};

async function handleInitModel() {
  Object.assign(model, createDefaultModel());
  Object.assign(optionsValue, createOptionsModel());

  if (!props.rowData) return;

  getOrgTreeOptions();

  if (props.operateType === 'edit' && props.rowData) {
    if (props.rowData.leaderUserId) {
      const params = {
        userId: Number(props.rowData.leaderUserId)
      };
      const { data, error } = await fetchUserOptionsPage(params);

      if (!error) {
        userOptions.value = data.records;
        optionsValue.page = data.current;
        optionsValue.pageSize = data.size;
        optionsValue.itemCount = data.total;
      }
    } else {
      getUserOptions('');
    }

    Object.assign(model, props.rowData);
  } else {
    getUserOptions('');
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" :mask-closable="false" class="w-200">
    <NScrollbar class="max-h-200 pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="auto">
        <NFormItem :label="$t('page.manage.org.parentId')" path="name">
          <NTreeSelect
            v-model:value="model.parentId"
            :options="orgOptions"
            :placeholder="$t('page.manage.org.form.parentId')"
            key-field="value"
          />
        </NFormItem>
        <NFormItem :label="$t('page.manage.org.name')" path="name">
          <NInput v-model:value="model.name" :placeholder="$t('page.manage.org.form.name')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.org.sort')" path="sort">
          <NInputNumber v-model:value="model.sort" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.org.leader')" path="leaderUserId">
          <NSelect
            v-model:value="model.leaderUserId"
            :options="userOptions"
            :placeholder="$t('page.manage.org.form.leader')"
            filterable
            :loading="userOptionsLoading"
            clearable
            remote
            @search="getUserOptions"
            @clear="optionsClear"
          >
            <template #action>
              <div class="flex-end">
                <NPagination
                  v-model:page="optionsValue.page"
                  v-model:page-size="optionsValue.pageSize"
                  show-size-picker
                  :user-page="optionsValue.itemCount"
                  :page-sizes="[10, 20, 30, 50, 100]"
                  :item-count="optionsValue.itemCount"
                  @update:page="handleOptionsPage"
                  @update:page-size="handleOptionsPageSize"
                >
                  <template #prefix="{ itemCount }">共 {{ itemCount }} 条</template>
                </NPagination>
              </div>
            </template>
          </NSelect>
        </NFormItem>
        <NFormItem :label="$t('page.manage.org.phone')" path="phone">
          <NInput v-model:value="model.phone" :placeholder="$t('page.manage.org.form.phone')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.org.email')" path="email">
          <NInput v-model:value="model.email" :placeholder="$t('page.manage.org.form.email')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.org.status')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio
              v-for="item in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </NRadioGroup>
        </NFormItem>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped>
.flex-end {
  display: flex;
  justify-content: flex-end;
}
</style>
